package org.androidpn.activity;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.androidpn.HospitalClientApplication;
import org.androidpn.R;
import org.androidpn.adapter.MessageListAdapter;
import org.androidpn.http.HttpApi;
import org.androidpn.model.CTalkList;
import org.androidpn.model.CTalkMessage;
import org.androidpn.model.CUserInfo;
import org.androidpn.model.NetModel;
import org.androidpn.net.BitmapUtil;
import org.androidpn.net.NetworkAgent;
import org.androidpn.net.ThreadPoolAgent;
import org.androidpn.utils.AppCache;
import org.androidpn.utils.ConstanceUtil;
import org.androidpn.utils.JsonUtil;
import org.androidpn.utils.ToastUtil;

import com.android.volley.VolleyError;

import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class TalkingActivity extends BaseActivity implements OnClickListener {
	private ListView lvContent;
	private TextView tvName;
	private ImageView ivBack;
	private EditText etTextInput;
	private ImageView ivPicInput;
	private CTalkList cTalkList;
	private CUserInfo cUserInfo;
	private String receiverTelephone;
	private int page = 1;
	private int size = 1000;
	private static final int MSG_UPDATE_USER_ICON = 0x0100;

	private List<CTalkMessage> messageList = new ArrayList<CTalkMessage>();
	TalkBroadcastReceiver talkBroadcastReceiver = new TalkBroadcastReceiver();
	MessageListAdapter adapter;
	public final int IMAGE_CODE = 3;
	private final String IMAGE_TYPE = "image/*";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.talkingactivity_layout);
		receiverTelephone =getIntent().getStringExtra("receiverTelephone");
		lvContent = (ListView) findViewById(R.id.lv_msg_content);
		tvName = (TextView) findViewById(R.id.tv_name);
		ivBack = (ImageView) findViewById(R.id.iv_back);
		etTextInput = (EditText) findViewById(R.id.et_text_input);
		ivPicInput = (ImageView) findViewById(R.id.pic_input);
		ivPicInput.setOnClickListener(this);
		cTalkList = (CTalkList) getIntent().getSerializableExtra("ctalklist");
		ivBack.setOnClickListener(this);
         		
		cUserInfo = AppCache.getInstance().getUseInfo();
		adapter = new MessageListAdapter(this);
		adapter.setMsgList(messageList);
		adapter.setcTalkList(cTalkList);
		lvContent.setAdapter(adapter);
        if(cTalkList != null){
        	initDate();
        	//更新
        	String othertelephone="";
        	if(cTalkList.getFriend_telephone().contentEquals(cUserInfo.getTelephone())){
        		othertelephone =cTalkList.getMy_telephone();
        	}else{
        		othertelephone =cTalkList.getFriend_telephone();
        	}
        	org.androidpn.listener.CommentResponseListener listener =new org.androidpn.listener.CommentResponseListener();
        	HttpApi.updateUnreadMessage(othertelephone,cUserInfo.getTelephone() , listener, listener);
        }
		etTextInput.setOnEditorActionListener(new TextView.OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				/* 判断是否是“GO”键 */
				if (actionId == EditorInfo.IME_ACTION_SEND) {
					/* 隐藏软键盘 */
					InputMethodManager imm = (InputMethodManager) v.getContext()
							.getSystemService(Context.INPUT_METHOD_SERVICE);
					if (imm.isActive()) {
						imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
					}
					String msgcontent = etTextInput.getText().toString();
					if (TextUtils.isEmpty(msgcontent)) {
						ToastUtil.showShortToast(TalkingActivity.this, "发送消息不能为空");
						return false;
					}
					// 发送消息
					CommentResponseListener listener = new CommentResponseListener();
					HttpApi.sendTextMessage(cUserInfo.getTelephone(), receiverTelephone, msgcontent, listener,
							listener);
					CTalkMessage cTalkMessage = new CTalkMessage();
					cTalkMessage.setMessage_content(msgcontent);
					cTalkMessage.setMessage_type(ConstanceUtil.MESSAGETYPE_TEXT);
					cTalkMessage.setSend_time(new Date());
					cTalkMessage.setReceiver_telephone(receiverTelephone);
					cTalkMessage.setSender_telephone(cUserInfo.getTelephone());
					messageList.add(cTalkMessage);
					adapter.notifyDataSetChanged();
					lvContent.setSelection(messageList.size() - 1);
					etTextInput.setText("");
					return true;
				}
				return false;
			}

		});
		
		GetTalkListMesgResponseListener getmsgListener = new GetTalkListMesgResponseListener();
		HttpApi.getTalkMessgeList(cUserInfo.getTelephone(), receiverTelephone, page + "", size + "", getmsgListener,
				getmsgListener);
	}
    private void initDate(){
	if (cUserInfo.getTelephone().equals(cTalkList.getMy_telephone())) {
		tvName.setText(cTalkList.getFriend_name());
		receiverTelephone = cTalkList.getFriend_telephone();
	} else {
		tvName.setText(cTalkList.getMy_name());
		receiverTelephone = cTalkList.getMy_telephone();
	}
//	adapter.setMytlephone(receiverTelephone);
}
	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		RegisterBroadCastReceiver();
		super.onStart();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		UnregisterBroadCastReceiver();
		super.onDestroy();
	}

	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		switch (arg0.getId()) {

		case R.id.iv_back:
			this.finish();
			break;
		case R.id.pic_input:
			Intent getAlbum = new Intent(Intent.ACTION_GET_CONTENT);
			getAlbum.setType(IMAGE_TYPE);
			startActivityForResult(getAlbum, IMAGE_CODE);
			break;

		default:
			break;
		}
	}

	class GetTalkListMesgResponseListener
			implements com.android.volley.Response.Listener<String>, com.android.volley.Response.ErrorListener {

		@Override
		public void onErrorResponse(VolleyError error) {
			// TODO Auto-generated method stub
			ToastUtil.showShortToast(TalkingActivity.this, "网络异常");
		}

		@Override
		public void onResponse(String response) {
			// TODO Auto-generated method stub
			NetModel netModel = JsonUtil.parseObject(response, NetModel.class);
			if (netModel.getCode() == ConstanceUtil.REQUEST_SUCCESS) {
				List<CTalkMessage> templist = JsonUtil.parseArray(netModel.getContent(), CTalkMessage.class);
				Collections.reverse(templist);
				messageList.addAll(templist);
				if(adapter.getcTalkList()!=null){
				adapter.notifyDataSetChanged();
				}else{
		        	if(cUserInfo!=null && !TextUtils.isEmpty(receiverTelephone)){
		        	GetSingleTalkListMesgResponseListener listener =new GetSingleTalkListMesgResponseListener();
		        	HttpApi.getSingleTalkList(cUserInfo.getTelephone(), receiverTelephone, listener, listener);
		        	}
				}
			} else {
			}
		}

	}

	class CommentResponseListener
			implements com.android.volley.Response.Listener<String>, com.android.volley.Response.ErrorListener {

		@Override
		public void onResponse(String response) {
			// TODO Auto-generated method stub
		}

		@Override
		public void onErrorResponse(VolleyError error) {
			// TODO Auto-generated method stub
			ToastUtil.showShortToast(HospitalClientApplication.getmInstance(), "网络异常");

		}
	}

	public void RegisterBroadCastReceiver() {
		IntentFilter filter = new IntentFilter();
		filter.addAction(ConstanceUtil.TALK_ACTIVITY_BROAD);
		registerReceiver(talkBroadcastReceiver, filter);
	}

	public void UnregisterBroadCastReceiver() {
		unregisterReceiver(talkBroadcastReceiver);
	}

	class TalkBroadcastReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context arg0, Intent arg1) {
			// TODO Auto-generated method stub
			CTalkMessage cTalkMessage = (CTalkMessage) arg1.getSerializableExtra("talkmessage");
			// ToastUtil.showShortToast(TalkingActivity.this, "talking Activity
			// 接收到广播:"+cTalkMessage.getMessage_content());
			if (cTalkMessage != null) {
				messageList.add(cTalkMessage);
				adapter.notifyDataSetChanged();
				if (messageList != null && messageList.size() > 0) {
					lvContent.setSelection(messageList.size() - 1);
				}
			}
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode != RESULT_OK) { // 此处的 RESULT_OK 是系统自定义得一个常量
			Log.e("wulianshu", "ActivityResult resultCode error");
			return;
		}

		if (requestCode == IMAGE_CODE) {

			// 外界的程序访问ContentProvider所提供数据 可以通过ContentResolver接口
			ContentResolver resolver = getContentResolver();
			// 此处的用于判断接收的Activity是不是你想要的那个
			if (requestCode == IMAGE_CODE) {
				try {
					Uri originalUri = data.getData(); // 获得图片的uri
					final Bitmap bitmap = MediaStore.Images.Media.getBitmap(resolver, originalUri);
					// 显得到bitmap图片
					// 这里开始的第二部分，获取图片的路径：
					String[] proj = { MediaStore.Images.Media.DATA };
					// 好像是android多媒体数据库的封装接口，具体的看Android文档
					@SuppressWarnings("deprecation")
					Cursor cursor = managedQuery(originalUri, proj, null, null, null);
					// 按我个人理解 这个是获得用户选择的图片的索引值
					int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
					// 将光标移至开头 ，这个很重要，不小心很容易引起越界

					cursor.moveToFirst();
					// 最后根据索引值获取图片路径
					String path = cursor.getString(column_index);
					CTalkMessage cTalkMessage = new CTalkMessage();
					cTalkMessage.setMessage_content(path);
					cTalkMessage.setMessage_type(ConstanceUtil.MESSAGETYPE_PIC);
					cTalkMessage.setReceiver_telephone(receiverTelephone);
					cTalkMessage.setSender_telephone(cUserInfo.getTelephone());
					cTalkMessage.setSend_time(new Date());
					cTalkMessage.isLocaldata = true;
					messageList.add(cTalkMessage);
					adapter.notifyDataSetChanged();
					if (messageList != null && messageList.size() > 0) {
						lvContent.setSelection(messageList.size() - 1);
					}
					if (bitmap != null) {
						ThreadPoolAgent.executeAsynTask(new Runnable() {
							@Override
							public void run() {
								HashMap<String, String> params = new HashMap<String, String>();
								params.put("sendertelephone", cUserInfo.getTelephone());
								params.put("receivertelephone", receiverTelephone);
								params.put("msgcontent", "pic");
								params.put("msgtype", "1");
								HashMap<String, byte[]> bytes = new HashMap<String, byte[]>();
								bytes.put("icons", BitmapUtil.bitmap2Bytes(bitmap));
								NetModel netModel = NetworkAgent.request(params,
										ConstanceUtil.REQUEST_SEND_IAMGE_MESSAGE, bytes);
								// Message msg = new Message();
								// msg.what = MSG_UPDATE_USER_ICON;
								// msg.obj = netModel;
								// sendMessage(msg);
								bitmap.recycle();
							}
						});
					}
				} catch (IOException e) {
					Log.e("wulianshu", e.toString());

				}

			}

		}

		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	protected void onHandleMessage(Message msg) {
		// TODO Auto-generated method stub
		switch (msg.what) {
		case MSG_UPDATE_USER_ICON: {
			NetModel netModel = (NetModel) msg.obj;
			if (netModel != null) {
				try {
					if (netModel.getCode() == ConstanceUtil.REQUEST_SUCCESS) {
						CTalkMessage cTalkMessage = JsonUtil.parseObject(netModel.getContent(), CTalkMessage.class);
						messageList.add(cTalkMessage);
						adapter.notifyDataSetChanged();
					}
				} catch (Exception e) {

				}
			}
		}
		}
	}
	
	class GetSingleTalkListMesgResponseListener
	implements com.android.volley.Response.Listener<String>, com.android.volley.Response.ErrorListener {

@Override
public void onErrorResponse(VolleyError error) {
}

@Override
public void onResponse(String response) {
	// TODO Auto-generated method stub
	NetModel netModel = JsonUtil.parseObject(response, NetModel.class);
	if (netModel.getCode() == ConstanceUtil.REQUEST_SUCCESS) {
		cTalkList = JsonUtil.parseObject(netModel.getContent(), CTalkList.class);
		adapter.setcTalkList(cTalkList);
		initDate();
		adapter.notifyDataSetChanged();
	} else {
		
	}
}

}

}
